package com.yeskery.nut.extend.oauth;

import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.RequestApplicationContext;
import com.yeskery.nut.core.Session;

/**
 * 基于session的TokenStore实现
 * @author YESKERY
 * 2024/10/21
 */
public class SessionTokenStore implements TokenStore {
    @Override
    public boolean save(String accessToken, String value, long expires) {
        getSession().addAttribute(accessToken, value);
        return true;
    }

    @Override
    public String get(String accessToken) {
        return (String) getSession().getAttribute(accessToken);
    }

    @Override
    public boolean validate(String accessToken) {
        return get(accessToken) != null;
    }

    @Override
    public boolean delete(String accessToken) {
        getSession().removeAttribute(accessToken);
        return true;
    }

    /**
     * 获取当前请求的Session
     * @return 当前请求的Session
     */
    private Session getSession() {
        return RequestApplicationContext.getResource(RequestApplicationContext.REQUEST_HOLDER_KEY, Request.class).getSession();
    }
}
